﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;

namespace CoolCode.Web.UI.Views.Home
{
    public partial class Regedit : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            regedit.CreatingUser += new LoginCancelEventHandler(regedit_CreatingUser);
            //regedit.CreatedUser += new EventHandler(regedit_CreatedUser); 
        }

        void regedit_CreatingUser(object sender, LoginCancelEventArgs e)
        {
            e.Cancel = true;
            MembershipCreateStatus status ;
            var member= Membership.CreateUser(regedit.UserName, regedit.Password, regedit.Email, "Do u like asp.net?", "Yes, I like!", true, out status);
            switch (status)
            {
                case MembershipCreateStatus.Success :
                    regedit.InstructionText = string.Empty;
                    FormsAuthentication.SetAuthCookie(regedit.UserName, false);
                    break;
                case MembershipCreateStatus.InvalidUserName:
                    regedit.InstructionText = "无效用户名";
                    break;
                case MembershipCreateStatus.DuplicateUserName:
                    regedit.InstructionText = "用户名已经被注册";
                    break;
                case  MembershipCreateStatus.InvalidPassword:
                    regedit.InstructionText = "无效密码";
                    break;
                default:
                    regedit.InstructionText = "未知错误，请重新注册";
                    break;
            }
            if (status == MembershipCreateStatus.Success)
            {
                if (!Roles.IsUserInRole(regedit.UserName, Role.DefaultUserRole))
                {
                    if (!Roles.RoleExists(Role.DefaultUserRole))
                    {
                        Roles.CreateRole(Role.DefaultUserRole);
                    }
                    Roles.AddUserToRole(regedit.UserName, Role.DefaultUserRole);
                }
                this.ViewHome();
            }
            if (!string.IsNullOrEmpty(regedit.InstructionText))
            { 
                this.ErrorMessage.Text = regedit.InstructionText;
            }
        }

        //void regedit_CreatedUser(object sender, EventArgs e)
        //{
        //    if (!Roles.IsUserInRole(regedit.UserName, Role.DefaultUserRole))
        //    {
        //        Roles.AddUserToRole(regedit.UserName, Role.DefaultUserRole);
        //    }
        //    this.ViewHome();
        //}
    }
}
